// Websocket.js
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

/**
 * 创建WebSocket连接并订阅指定主题
 * @param {string} url WebSocket服务器地址
 * @param {Array<{topic: string, callback: Function}>} subscriptions 订阅配置数组
 * @returns {{ disconnect: () => void }} 包含断开连接方法的对象
 */
export const createWebSocketConnection = (url, subscriptions) => {
    const socket = new SockJS(url);
    const stompClient = new Client({
        webSocketFactory: () => socket,
        reconnectDelay: 5000,
        onConnect: () => {
            console.log(`WebSocket Connected to ${url} ${subscriptions}`);
            subscriptions.forEach(({ topic, callback }) => {
                stompClient.subscribe(topic, (message) => {
                    try {
                        const msgData = JSON.parse(message.body);
                        callback(msgData);
                    } catch (e) {
                        console.error('消息解析失败:', e);
                    }
                });
            });
        },
        onStompError: (frame) => {
            console.error('STOMP协议错误:', frame.headers.message);
        },
        onWebSocketClose: (event) => {
            console.log('WebSocket连接关闭:${url}', event);
        }
    });

    stompClient.activate();

    return {
        disconnect: () => {
            if (stompClient) {
                stompClient.deactivate();
                console.log(`WebSocket连接已断开: ${url}`);
            }
        }
    };
};